package com.doradance.app.appactivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.android.internal.http.multipart.FilePart;
import com.android.internal.http.multipart.Part;
import com.android.tu.loadingdialog.LoadingDailog;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.MultipartRequest;
import com.doradance.account.utils.ShareUtil;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.AddBabyEntity;
import com.doradance.entity.UserHomeEntity;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.datetimepicker.DatePickerFragment;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.io.SharePreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import static com.doradance.account.ui.LoginPhoneActivity.LOGINADD;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_COVER_TAKE_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_SELECT_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_TAKE_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_ZOOM_PHOTO;
import static com.doradance.app.appactivity.NickNameActivity.BACKMODIFYNICKNAME;
import static com.doradance.app.appactivity.NickNameActivity.MODIFYNICKNAME;
import static com.doradance.app.appactivity.PersititySignActivity.BACKMODIFYPERSITITYSIGN;
import static com.doradance.app.appactivity.PersititySignActivity.MODIFYPERSITITYSIGN;
import static com.doradance.app.mine.MineFragment.MINEADD;
import static com.doradance.app.mine.MineFragment.MINEMODIFY;

public class AddBabyActivity extends BaseActivity {
    @Bind(R.id.tv_birthday)
    TextView mTvBirthday;
    @Bind(R.id.tv_persitity_sign)
    EditText mTvPersititySign;
    @Bind(R.id.iv_head)
    CircleImageView mIvHead;
    @Bind(R.id.rb_man)
    RadioButton mRbMan;
    @Bind(R.id.rb_woman)
    RadioButton mRbWoman;
    @Bind(R.id.iv_cover)
    ImageView mIvCover;
    @Bind(R.id.tv_nick_name)
    TextView mTvNickName;
    LoadingDailog upDialog;
    private UserHomeEntity.BabiesBean babiesBean;
    private String gender;
    public static final int HEADER = 5;
    public static final int COVER = 6;
    public static AddBabyActivity instance = null;
    public AlertDialogFragment singOutDialogFrag;
    int other =-1;

    private LQRPhotoSelectUtils mLqrPhotoSelectUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;

        other = getIntent().getIntExtra("other", -1);
        if(other==MINEADD){
            initToolsBar(1);
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","headUrl","");
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","coverUrl","");
        }else if(other==LOGINADD){
            initToolsBar(1);
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","headUrl","");
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","coverUrl","");
        }else if(other==MINEMODIFY)
        {
            initToolsBar(2);
            babiesBean = (UserHomeEntity.BabiesBean) getIntent().getSerializableExtra("babiesBean");
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","headUrl",babiesBean.getAvatar());
            SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","coverUrl",babiesBean.getCover());
            SharePreferenceUtil.saveString(AddBabyActivity.this, "sign", "sign",babiesBean.getSign());
            mTvBirthday.setText(babiesBean.getBirthday());
            mTvNickName.setText(babiesBean.getNick_name());
            mTvPersititySign.setText(babiesBean.getSign());
            if(babiesBean.getGender()==2){
                mRbWoman.setChecked(true);
            }else{
                mRbMan.setChecked(true);
            }
            getCustomToolbar().addRightButton("删除", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DeleteBaby();
                }
            });
        }
        if(!TextUtils.isEmpty(getHeadUrl())){
            Glide.with(AddBabyActivity.this).load(getHeadUrl()).into(mIvHead);
        }
        if(!TextUtils.isEmpty(getCoverUrl())){
            Glide.with(AddBabyActivity.this).load(getCoverUrl()).into(mIvCover);
        }
    }
    //删除宝宝
    private void DeleteBaby() {
        //退出登录
        singOutDialogFrag = new AlertDialogFragment();
        singOutDialogFrag.setMessage("确定要删除宝宝吗？")
                .setNegativeButton("取消", true, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        singOutDialogFrag.dismiss();
                    }
                })
                .setPositiveButton("确定", false, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    deleteBaby();
                    }
                }).show(getSupportFragmentManager());

    }

    private void deleteBaby() {
        MyHttpRequest request = new MyHttpRequest(AddBabyActivity.this);
        String selectId = ShareUtil.getBabyId();
        int id = babiesBean.getId();
        if(selectId.equals(id+"")){
            EasyToast.showToast(getApplicationContext(),"当前选中宝宝不可删除");
            singOutDialogFrag.dismiss();
            return;
        }
        String deleteUrl = String.format(UrlCenter.BABY_DELETE, id);
        request.delete(deleteUrl, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                getMineInfo();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(),strMsg);
            }
        });
    }

    private void init(Boolean isTake,final int type11) {
        // 1、创建LQRPhotoSelectUtils（一个Activity对应一个LQRPhotoSelectUtils）
        mLqrPhotoSelectUtils = new LQRPhotoSelectUtils(this, new LQRPhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri,int type) {
                // 4、当拍照或从图库选取图片成功后回调
                sendRequest(type11,outputFile.getAbsolutePath());
            }
        }, true);//true裁剪，false不裁剪
        if(isTake==true){
            mLqrPhotoSelectUtils.takePhoto(type11);
        }else{
            mLqrPhotoSelectUtils.selectPhoto(type11);
        }
    }

    @SuppressLint("ResourceType")
    private void initToolsBar(int type) {
        if(type==1){
            getCustomToolbar().setTitle(getString(R.string.add_baby));
        }else{
            getCustomToolbar().setTitle("修改宝宝信息");
        }
        getCustomToolbar().addLeftImageButton(R.mipmap.back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, AddBabyActivity.class);
        activity.startActivity(intent);
    }
    public static void start(Activity activity,int other) {
        Intent intent = new Intent(activity, AddBabyActivity.class);
        intent.putExtra("other", other);
        activity.startActivity(intent);
    }

    public static void start(Activity activity,UserHomeEntity.BabiesBean babiesBean,int other) {
        Intent intent = new Intent(activity, AddBabyActivity.class);
        intent.putExtra("babiesBean", babiesBean);
        intent.putExtra("other", other);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.activity_add_baby, null);
        return inflate;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQ_TAKE_PHOTO||requestCode==REQ_SELECT_PHOTO||requestCode==REQ_ZOOM_PHOTO){
            mLqrPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }else if (requestCode == MODIFYNICKNAME && resultCode == BACKMODIFYNICKNAME) {
            mTvNickName.setText(data.getStringExtra("nickback"));
        } else if (requestCode == MODIFYPERSITITYSIGN && resultCode == BACKMODIFYPERSITITYSIGN) {
            mTvPersititySign.setText(data.getStringExtra("signback"));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 自己通过消息队列上传图片到服务器
     */
    private void sendRequest(final int type,String url) {
        //获取队列
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(this)
                .setMessage("上传中...")
                .setCancelable(true)
                .setCancelOutside(true);

        upDialog = loadBuilder.create();
        upDialog.show();

        File file = new File(url);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        List<Part> partList = new ArrayList<Part>();
        try {
            partList.add(new FilePart("image", file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //生成请求
        MultipartRequest profileUpdateRequest = new MultipartRequest(UrlCenter.IMGAGE, partList.toArray(new Part[partList.size()]), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                JSONObject jobj = null;
                try {
                    jobj = new JSONObject(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String url = jobj.optString("url");
                upDialog.cancel();
                if(type==HEADER){
                    SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","headUrl",url);
                    Glide.with(AddBabyActivity.this).load(url).into(mIvHead);
                }else{
                    SharePreferenceUtil.saveString(AddBabyActivity.this,"sign","coverUrl",url);
                    Glide.with(AddBabyActivity.this).load(url).into(mIvCover);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                upDialog.cancel();
            }
        });
        //将请求加入队列
        requestQueue.add(profileUpdateRequest);
    }

    @OnClick({R.id.iv_head, R.id.ll_birthday, R.id.ll_persitity_sign, R.id.ll_cover, R.id.ll_nick_name,
            R.id.add_next, R.id.tv_persitity_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                showIOSAlertFrag(HEADER);
                break;
            case R.id.ll_birthday:
                final DatePickerFragment frag = new DatePickerFragment(Calendar.getInstance());
                frag.setOnDateSelectedListener(new DatePickerFragment.OnDateSelectedListener() {
                    @Override
                    public void onDateSelected(int year, int monthOfYear, int dayOfMonth) {
                        mTvBirthday.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
                        frag.dismiss();
                    }
                });
                frag.show(AddBabyActivity.this.getSupportFragmentManager());
                break;
            case R.id.ll_persitity_sign:
                PersititySignActivity.start(AddBabyActivity.this, mTvPersititySign.getText().toString().trim());
                break;
            case R.id.ll_cover:
                showIOSAlertFrag(COVER);
                break;
            case R.id.ll_nick_name:
                NickNameActivity.start(AddBabyActivity.this, mTvNickName.getText().toString().trim());
                break;
            case R.id.add_next:
                addNext();
                break;
            case R.id.tv_persitity_sign:
                PersititySignActivity.start(AddBabyActivity.this, mTvPersititySign.getText().toString().trim());
                break;
        }
    }

    //下一步
    private void addNext() {
        if (TextUtils.isEmpty(getNickname())) {
            EasyToast.showToast(getApplicationContext(), "请填写昵称");
            return;
        } else if (!mRbMan.isChecked() && !mRbWoman.isChecked()) {
            EasyToast.showToast(getApplicationContext(), "请选择性别");
            return;
        } else if (TextUtils.isEmpty(getBirthday())) {
            EasyToast.showToast(getApplicationContext(), "请选择生日日期");
            return;
        } else if (TextUtils.isEmpty(SharePreferenceUtil.getString(AddBabyActivity.this, "sign", "sign"))||TextUtils.isEmpty(mTvPersititySign.getText().toString().trim())) {
            EasyToast.showToast(getApplicationContext(), "请输入个性签名");
            return;
        }
        if(mRbMan.isChecked()){
            gender=1+"";
        }else{
            gender=2+"";
        }
        if(TextUtils.isEmpty(getHeadUrl())){
            EasyToast.showToast(getApplicationContext(),"请上传头像");
            return;
        }else if(TextUtils.isEmpty(getCoverUrl())){
            EasyToast.showToast(getApplicationContext(),"请上传宝宝封面");
            return;
        }else if(other==MINEADD){
            SelsectLabelActivity.start(this,MINEADD,getNickname(),getHeadUrl(),getCoverUrl(),getBirthday(),gender,SharePreferenceUtil.getString(AddBabyActivity.this, "sign", "sign"));
        }else if (other==LOGINADD){
            SelsectLabelActivity.start(this,LOGINADD,getNickname(),getHeadUrl(),getCoverUrl(),getBirthday(),gender,SharePreferenceUtil.getString(AddBabyActivity.this, "sign", "sign"));
        }else if(other==MINEMODIFY){
            SelsectLabelActivity.start(this,babiesBean.getUser_id(),babiesBean.getId(),MINEMODIFY,getNickname(),getHeadUrl(),getCoverUrl(),getBirthday(),gender,SharePreferenceUtil.getString(AddBabyActivity.this, "sign", "sign"));
        }
    }



    private Uri createNewPictureUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(FileManager.getImagePath(context) + File.separator + "IMG_" + timeStamp + ".jpg");
        return Uri.fromFile(mediaFile);
    }

    @SuppressLint("NewApi")
    private void showIOSAlertFrag(final int type) {
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        String[] strArr = new String[]{"拍照", "从照片库选择"};
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    //拍照
                    case 0:
                        // 3、调用拍照方法
                        if(type==HEADER){
                            PermissionGen.with(AddBabyActivity.this)
                                    .addRequestCode(REQ_TAKE_PHOTO)
                                    .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.CAMERA
                                    ).request();
                        }else{
                            PermissionGen.with(AddBabyActivity.this)
                                    .addRequestCode(REQ_COVER_TAKE_PHOTO)
                                    .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.CAMERA
                                    ).request();
                        }

                        break;
                    //相册
                    case 1:
                        // 3、调用从图库选取图片方法
                        if(type==HEADER){
                            PermissionGen.needPermission(AddBabyActivity.this,
                                    LQRPhotoSelectUtils.REQ_SELECT_PHOTO,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE}
                            );
                        }else{
                            PermissionGen.needPermission(AddBabyActivity.this,
                                    LQRPhotoSelectUtils.REQ_COVER_SELECT_PHOTO,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                            Manifest.permission.WRITE_EXTERNAL_STORAGE}
                            );
                        }

                        break;
                }
                diaFrag.dismiss();
            }
        }, strArr).show(getSupportFragmentManager());
    }

    //头像拍照
    @PermissionSuccess(requestCode = REQ_TAKE_PHOTO)
    private void takePhoto() {
        init(true,HEADER);
    }

    //封面拍照
    @PermissionSuccess(requestCode = LQRPhotoSelectUtils.REQ_COVER_TAKE_PHOTO)
    private void coverTakePhoto() {
        init(true,COVER);
    }


    @PermissionSuccess(requestCode = LQRPhotoSelectUtils.REQ_SELECT_PHOTO)
    private void selectPhoto() {

        init(false,HEADER);
    }

    @PermissionSuccess(requestCode = LQRPhotoSelectUtils.REQ_COVER_SELECT_PHOTO)
    private void coverSelectPhoto() {
        init(false,COVER);
    }


    private void getMineInfo() {
        MyHttpRequest request = new MyHttpRequest(AddBabyActivity.this);
        request.get(UrlCenter.USERS_HOME, null, new DataRequestListener<UserHomeEntity>(UserHomeEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(UserHomeEntity o) {
                super.onSuccess(o);
                finish();
                EventBus.getDefault().post(new AddBabyEntity(o));
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    public String getHeadUrl(){
        return SharePreferenceUtil.getString(AddBabyActivity.this,"sign","headUrl");
    }
    public String getCoverUrl(){
        return SharePreferenceUtil.getString(AddBabyActivity.this,"sign","coverUrl");
    }

    public String getNickname() {
        return mTvNickName.getText().toString().trim();
    }

    public String getBirthday() {
        return mTvBirthday.getText().toString().trim();
    }
}
